package util;

import entity.*;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

/**
 * Hibernate Utility class with a convenient method to get Session Factory object.
 *
 */
public class HibernateUtil {

    private static final SessionFactory sessionFactory;
    
    static {
        try {
            // Create the SessionFactory from standard (hibernate.cfg.xml) 
            // config file.
            AnnotationConfiguration ac = new AnnotationConfiguration();
            //Добавление аннотированных классов сущностей.
            ac.addAnnotatedClass(OrgUnit.class);
            ac.addAnnotatedClass(OrgUnitPost.class);
            ac.addAnnotatedClass(Person.class);
            ac.addAnnotatedClass(Phone.class);
            ac.addAnnotatedClass(PhoneType.class);
            ac.addAnnotatedClass(Post.class);
            ac.addAnnotatedClass(Room.class);
            ac.addAnnotatedClass(OrgUnitType.class);
            ac.addAnnotatedClass(User.class);
            sessionFactory = ac.configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Log the exception. 
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
  
    public static Session getSession()
            throws HibernateException {
        return sessionFactory.openSession();
    }
}